﻿using System;
using System.Collections.Concurrent;
using UnityEngine;

namespace Carcassonne.Network
{
    public static class MainThreadLoop
    {
        public static ConcurrentQueue<ThreadAction> Actions = new ConcurrentQueue<ThreadAction>();

        public static float MinInvokeTime = 0;
        public static ConcurrentQueue<ThreadAction> DelayActions = new ConcurrentQueue<ThreadAction>();

        public static void Add(string name, Action action)
        {
            Actions.Enqueue(new ThreadAction(name, action, 0));
        }

        public static void AddDelay(string name, Action action, float time, int lifeTime = 0)
        {
            Actions.Enqueue(new ThreadAction(name, action, -time, lifeTime));
        }

        public static void AddDelayMain(ThreadAction action)
        {
            if (DelayActions.IsEmpty)
            {
                MinInvokeTime = action.Time;
            }
            else
            {
                MinInvokeTime = Mathf.Min(MinInvokeTime, action.Time);
            }
        }
    }

    public struct ThreadAction
    {
        public string Name;

        public Action Action;

        public int LifeTime;

        public float Time;

        public ThreadAction(string name, Action action, float time)
        {
            Name = name;
            Action = action;
            LifeTime = 0;
            Time = time;
        }

        public ThreadAction(string name, Action action, float time, int lifeTime)
        {
            Name = name;
            Action = action;
            LifeTime = lifeTime;
            Time = time;
        }
    }
}
